import { Component, Input, OnInit } from '@angular/core';
import { PerfectScrollbarConfigInterface } from 'ngx-perfect-scrollbar';

import { trigger, state, style, transition, animate } from '@angular/animations';
import { Router } from '@angular/router';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
  animations: [
    trigger('slide', [state('up', style({ height: 0 })), state('down', style({ height: '*' })), transition('up <=> down', animate(200))]),
  ],
})
export class SidebarComponent implements OnInit {
  public config: PerfectScrollbarConfigInterface = {};
  private toggled = false;

  private currMenu = null;

  @Input() data: any;
  @Input() hasBackgroundImage = true;

  constructor(private router: Router) {}

  ngOnInit() {}

  //

  toggleSidebar() {
    this.toggled = !this.toggled;
  }

  //
  toggle(currentMenu) {
    if (currentMenu.type === 'dropdown') {
      this.data.forEach((element) => {
        if (element === currentMenu) {
          currentMenu.active = !currentMenu.active;
        } else {
          element.active = false;
        }
      });
    }
  }

  getState(currentMenu) {
    if (currentMenu.active) {
      return 'down';
    } else {
      return 'up';
    }
  }

  onMenuClick(currentMenu, menu) {
    // 第一次点击，获取当前菜单组第一项
    if (!this.currMenu) {
      this.currMenu = menu.submenus[0];
      this.currMenu.active = true;
      if (this.router.url === currentMenu.link) {
        return;
      }
      // 有路由则跳转
      if (this.currMenu.link) {
        this.router.navigate([this.currMenu.link]);
      }
      return;
    }
    // 第2次之后点击，判断地址是否一样，一样则不操作
    if (this.currMenu.link === currentMenu.link) {
      return;
    }
    this.currMenu.active = false;
    this.currMenu = currentMenu;
    this.currMenu.active = true;

    if (currentMenu.link) {
      this.router.navigate([currentMenu.link]);
    }
  }
}
